package com.obrock;

import android.app.*;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.*;
import android.widget.AdapterView.OnItemSelectedListener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Rick
 */
public class EditBalance extends Activity implements /*OnClickListener, */ EditComplex.EditComplexListener, EditAnalytics.EditAnalyticsListener {

    static final int DIALOG_DATE = 21;
    static final int DIALOG_TIME = 22;
    static final int DIALOG_CONFIRM = 30;
    static final int ANALYTICS_ADD = 23;
    static final int ANALYTICS_EDIT = 24;
    static final int EDIT_ACCOUNT_FROM = 1;
    static final int EDIT_ACCOUNT_TO = 2;

    static final int DIRECTION_FROM = -1;
    static final int DIRECTION_TO = 1;


    EditText name;
    Spinner from;
    Spinner to;
    EditText amount;
    EditText remark;
    LinearLayout container;
    TableLayout listContainer;
    Context context;
    Balance balance;
    EditText number;
    EditText template;
    EditText key;
    CheckBox force;

    TextView balanceTo;
    TextView balanceFrom;
    TextView datePlace;
    TextView transferFrom;
    TextView transferTo;
    Button openFrom;

    TextView title;
    //TextView accountBalance;
    //TextView accountDetails;
    ImageView icon;

    Complex selected = null;

    LinearLayout blockTo;
    //LinearLayout blockComplex;
    TableLayout blockHeader;
    LinearLayout blockTemplate;
    TableLayout blockDate;
    LinearLayout blockAmount;

    LinearLayout blockPeriod;
    TableLayout blockPeriodN;
    Spinner prognosisType;
    TextView prognosisPeriodType;
    EditText prognosisPeriod;

    EditComplex editNameDialog = null;
    String savedName = "";
    long referenceID = -1;

    //Object objectFrom = null;
    //Object objectTo = null;
    ArrayAdapter adapterFrom = null;
    ArrayAdapter adapterTo = null;


    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.edit_balance);

        context = this;

        container = (LinearLayout) findViewById(R.id.container);
        listContainer = (TableLayout) findViewById(R.id.list_container);
        blockTo = (LinearLayout) findViewById(R.id.block_to);
        //blockComplex = (LinearLayout) findViewById(R.id.block_complex);
        blockHeader = (TableLayout) findViewById(R.id.block_header);
        blockDate = (TableLayout) findViewById(R.id.block_date);
        blockAmount = (LinearLayout) findViewById(R.id.block_amount);
        blockTemplate = (LinearLayout) findViewById(R.id.block_template);
        blockPeriod = (LinearLayout) findViewById(R.id.block_period);

        datePlace = (TextView) findViewById(R.id.date_place);
        balanceFrom = (TextView) findViewById(R.id.balance_from);
        balanceTo = (TextView) findViewById(R.id.balance_to);
        transferFrom = (TextView) findViewById(R.id.transfer_from);
        transferTo = (TextView) findViewById(R.id.transfer_to);

        title = (TextView) findViewById(R.id.title);
        //accountBalance = (TextView) findViewById(R.id.account_balance);
        //accountDetails = (TextView) findViewById(R.id.account_details);
        icon = (ImageView) findViewById(R.id.icon);

        prognosisType = (Spinner) findViewById(R.id.prognosis_type);
        blockPeriodN = (TableLayout) findViewById(R.id.block_period_n);
        prognosisPeriodType = (TextView) findViewById(R.id.prognosis_period_type);
        prognosisPeriod = (EditText) findViewById(R.id.prognosis_period);

        name = (EditText) findViewById(R.id.name);
        name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                savedName = name.getText().toString();
            }
        });

        from = (Spinner) findViewById(R.id.from);
        to = (Spinner) findViewById(R.id.to);
        amount = (EditText) findViewById(R.id.amount);
        amount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    if (Main.eval(amount.getText().toString(), 0.0) == 0) {
                        amount.setText("");
                    }
                }
            }
        });
        amount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().contains("=") || charSequence.toString().contains("\n")) {
                    double sum = balance.accountFrom == null
                            || balance.accountFrom.accountID == -1
                            ? 0.0
                            : balance.accountFrom.balance;
                    amount.setText(String.format("%.2f", Main.eval(charSequence.toString(), sum)));
                    try {
                        balance.amount = Main.eval(amount.getText().toString(), sum);
                    } catch (Exception e) {
                        balance.amount = 0.0;
                    }
                    balance.recalcComplex();
                    balance.recalcAnalytics();
                    refreshAnalytics();
                    refreshAmount();
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });

        remark = (EditText) findViewById(R.id.remark);
        number = (EditText) findViewById(R.id.number);
        template = (EditText) findViewById(R.id.template);
        key = (EditText) findViewById(R.id.key);
        force = (CheckBox) findViewById(R.id.force);
        force.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    balance.flags |= Balance.FLAG_FORCE_TRANSFER;
                } else {
                    balance.flags &= ~Balance.FLAG_FORCE_TRANSFER;
                }
            }
        });


        name.setInputType(name.getInputType() | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
        remark.setInputType(name.getInputType() | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);


        Button btnOK = (Button) findViewById(R.id.btnOk);
        btnOK.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                balance.name = name.getText().toString();
                balance.remark = remark.getText().toString();
                balance.number = number.getText().toString();
                balance.template = template.getText().toString();
                balance.key = key.getText().toString();
                balance.flags &= ~0xFF;
                balance.flags |= prognosisType.getSelectedItemPosition() + 1;
                balance.period = Integer.parseInt(prognosisPeriod.getText().toString());
                if (balance.period == 0) {
                    balance.period = 1;
                }

                try {
                    String a = amount.getText().toString();
                    double sum = balance.accountFrom == null
                            || balance.accountFrom.accountID == -1
                            ? 0.0
                            : balance.accountFrom.balance;
                    balance.amount = Main.eval(a, sum);
                } catch (Exception e) {
                    balance.amount = 0.0;
                }

                balance.recalcComplex();

                if (balance.type != Balance.TYPE_COMPLEX) {
                    if (referenceID != -1) {
                        balance.parentID = referenceID;
                        balance.flags |= Balance.FLAG_INHERIT_TRANSFER;
                    }
                } else {
                    balance.parentID = -1;
                    balance.flags &= ~Balance.FLAG_INHERIT_TRANSFER;
                }

                /*
                else {
                    for (Complex cc : balance.complex) {
                        if (cc.balance != null && (cc.balance.flags & Balance.FLAG_PERIOD_CREDIT) == 0) {
                            balance.parentID = cc.balance.parentID;
                            balance.flags |= Balance.FLAG_INHERIT_TRANSFER;
                            //break;
                        }
                    }
                }
                */

                if (balance.mode != Balance.MODE_PROGNOSIS && balance.accountFrom == null && balance.accountTo == null) {
                    Toast.makeText(getBaseContext(), getResources().getString(R.string.msg_account_notselected), Toast.LENGTH_SHORT).show();
                } else if (balance.mode != Balance.MODE_TEMPLATE && balance.amount == 0) {
                    Toast.makeText(getBaseContext(), getResources().getString(R.string.msg_account_notamount), Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent();
                    intent.putExtra("balance", balance);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });

        Button btnTime = (Button) findViewById(R.id.btnTime);
        btnTime.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                showDialog(DIALOG_TIME);
            }
        });

        Button btnDate = (Button) findViewById(R.id.btnDate);
        btnDate.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                showDialog(DIALOG_DATE);
            }
        });


        openFrom = (Button) findViewById(R.id.openFrom);
        openFrom.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent inent = new Intent(context, EditAccount.class);
                inent.putExtra("window_title", getResources().getString(R.string.prompt_account));

                if (balance.accountFrom != null && balance.accountFrom.accountID != -1) {
                    inent.putExtra("account", balance.accountFrom);
                    startActivityForResult(inent, EDIT_ACCOUNT_FROM);
                } else {
                    Toast.makeText(getBaseContext(), getResources().getString(R.string.msg_account_notselected), Toast.LENGTH_SHORT).show();
                }

            }
        });
        Button openTo = (Button) findViewById(R.id.openTo);
        openTo.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent inent = new Intent(context, EditAccount.class);
                inent.putExtra("window_title", getResources().getString(R.string.prompt_account));

                if (balance.accountTo != null && balance.accountTo.accountID != -1) {
                    inent.putExtra("account", balance.accountTo);
                    startActivityForResult(inent, EDIT_ACCOUNT_TO);
                } else {
                    Toast.makeText(getBaseContext(), getResources().getString(R.string.msg_account_notselected), Toast.LENGTH_SHORT).show();
                }

            }
        });

        Button btnComplex = (Button) findViewById(R.id.btnComplex);
        btnComplex.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                balance.name = name.getText().toString();
                balance.remark = remark.getText().toString();
                balance.amount = Main.eval(amount.getText().toString(), balance.amount);

                FragmentManager fm = getFragmentManager();
                editNameDialog = new EditComplex(Main.db, balance, null, adapterTo);
                editNameDialog.show(fm, "fragment_edit_complex");
                /*
                //balance.amount = Double.parseDouble(amount.getText().toString().replace(" ", "").replace(",", "."));
                if (balance.amount == 0) {
                    Toast.makeText(getBaseContext(), getResources().getString(R.string.msg_account_notamount), Toast.LENGTH_SHORT).show();
                    //} else if (balance.accountTo == null || balance.accountTo.accountID == -1) {
                    //    Toast.makeText(getBaseContext(), getResources().getString(R.string.msg_account_notselected), Toast.LENGTH_SHORT).show();
                } else {
                    balance.type = Balance.TYPE_COMPLEX;
                    balance.complex.add(new Complex(Main.db, balance));
                    balance.recalcComplex();
                    balance.recalcAnalytics();
                    refreshAnalytics();
                    refreshAmount();

                }
                */
            }
        });

        /*
        Button btnSwitch = (Button) findViewById(R.id.btnSwitch);
        btnSwitch.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                balance.name = name.getText().toString();
                balance.remark = remark.getText().toString();
                balance.amount = Main.eval(amount.getText().toString(), balance.amount);

                FragmentManager fm = getFragmentManager();
                editNameDialog = new EditComplex(Main.db, balance, null);
                editNameDialog.show(fm, "fragment_edit_complex");


                //blockComplex.setVisibility(View.GONE);
                //blockTo.setVisibility(View.VISIBLE);
            }
        });
        */


        /*
        List<String> tmp = new ArrayList<String>(0);
        tmp.add(getResources().getString(R.string.transfer_empty));
        for (Account ac : Main.accounts) {
            tmp.add(ac.name);
        }
        */

        /*
        List<Account> accounts = new ArrayList<Account>(0);
        accounts.add(new Account(Main.db, getResources().getString(R.string.transfer_empty)));
        accounts.addAll(Arrays.asList(Main.accounts));

        ArrayAdapter<Account> dataAdapter = new ArrayAdapter<Account>(this, android.R.layout.simple_spinner_item, accounts);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        */

        Account accountFrom = null;
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            balance = (Balance) extras.getSerializable("balance");
            if (extras.containsKey("account")) {
                accountFrom = (Account) extras.getSerializable("account");
            }
        }

        if (balance == null) {
            balance = new Balance(Main.db);
            balance.name = getResources().getString(R.string.transfer_title);
            balance.accountFrom = accountFrom;
        }

        adapterFrom = getAccountsAdapter(DIRECTION_FROM);
        adapterTo = getAccountsAdapter(DIRECTION_TO);

        from.setAdapter(adapterFrom);
        to.setAdapter(adapterTo);

        from.setOnItemSelectedListener(new OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> a, View v, int index, long pos) {
                balance.accountFrom = (Account) a.getAdapter().getItem(index);

                if (balance.accountFrom == balance.accountTo) {
                    Toast.makeText(getBaseContext(), getResources().getString(R.string.msg_account_selecterror), Toast.LENGTH_SHORT).show();
                }

                double currentAmount = 0.0;
                if (balance.accountFrom != null) {
                    if (balance.accountFrom.accountID == -1) {
                        balance.accountFrom = null;
                    } else {
                        currentAmount = balance.accountFrom.balance;
                    }
                }
                refreshAnalytics();

                balanceFrom.setText(String.format("%.2f", currentAmount));
                balanceFrom.setTextColor(Main.getAccountColor(balance.accountTo));
            }

            public void onNothingSelected(AdapterView<?> arg0) {
                //account.type = Account.TYPE_NORMAL;
            }
        });

        to.setOnItemSelectedListener(new OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> a, View v, int index, long pos) {
                Balance bal = null;
                referenceID = -1;
                if (a.getAdapter().getItem(index) instanceof Account) {
                    balance.accountTo = (Account) a.getAdapter().getItem(index);
                    if (balance.balanceID == -1) {
                        name.setText(savedName);
                    }
                } else {
                    bal = (Balance) a.getAdapter().getItem(index);
                    if (bal != null) {
                        referenceID = bal.parentID;
                        balance.accountTo = bal.accountTo;
                        if (balance.balanceID == -1) {
                            amount.setText(String.format("%.2f", bal.amount));
                            name.setText(bal.name);
                        }
                    }
                }

                if (balance.accountFrom == balance.accountTo) {
                    Toast.makeText(getBaseContext(), getResources().getString(R.string.msg_account_selecterror), Toast.LENGTH_SHORT).show();
                }

                double currentAmount = 0.0;
                if (balance.accountTo != null) {
                    if (balance.accountTo.accountID == -1) {
                        balance.accountTo = null;
                    } else {
                        currentAmount = balance.accountTo.balance;
                    }
                }
                refreshAnalytics();

                balanceTo.setText(String.format("%.2f", currentAmount));
                balanceTo.setTextColor(Main.getAccountColor(balance.accountTo));

            }

            public void onNothingSelected(AdapterView<?> arg0) {
                //account.type = Account.TYPE_NORMAL;
            }
        });


        if (accountFrom != null && balance.mode == Balance.MODE_NORMAL) {
            balanceFrom.setVisibility(View.GONE);
            transferFrom.setVisibility(View.GONE);
            from.setVisibility(View.GONE);
            openFrom.setVisibility(View.GONE);
            //accountBalance.setVisibility(View.VISIBLE);


            title.setText(accountFrom.name);
            //accountBalance.setText(getResources().getString(R.string.account_balance, accountFrom.balance));
            /*
            if (accountFrom.balanceCredit > 0 && accountFrom.balanceCredit != accountFrom.balance) {
                accountDetails.setText(getResources().getString(R.string.account_credit, accountFrom.balanceCredit));
            } else if (accountFrom.balanceDebt > 0 && accountFrom.balanceDebt != accountFrom.balance) {
                accountDetails.setText(getResources().getString(R.string.account_debt, accountFrom.balanceDebt));
            }
            */

            switch (accountFrom.type) {
                case Account.TYPE_NORMAL:
                    icon.setImageDrawable(getResources().getDrawable(R.drawable.wallet));
                    break;
                case Account.TYPE_DEBT:
                    icon.setImageDrawable(getResources().getDrawable(R.drawable.credit));
                    break;
                case Account.TYPE_CARD:
                    icon.setImageDrawable(getResources().getDrawable(R.drawable.card));
                    break;
            }

            icon.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (from.getVisibility() == View.VISIBLE) {
                        balanceFrom.setVisibility(View.GONE);
                        transferFrom.setVisibility(View.GONE);
                        from.setVisibility(View.GONE);
                        openFrom.setVisibility(View.GONE);
                    } else {
                        balanceFrom.setVisibility(View.VISIBLE);
                        transferFrom.setVisibility(View.VISIBLE);
                        from.setVisibility(View.VISIBLE);
                        openFrom.setVisibility(View.VISIBLE);
                    }
                }
            });

        } /*else {
            //accountBalance.setVisibility(View.GONE);
        }   */


        name.setText(balance.name);
        name.selectAll();
        from.setSelection(Main.getAccountIndex(balance.accountFrom) + 1);
        to.setSelection(Main.getAccountIndex(balance.accountTo) + 1);
        remark.setText(balance.remark);
        datePlace.setText(Main.datetimeFullString(balance.date));
        number.setText(balance.number);
        template.setText(balance.template);
        key.setText(balance.key);
        force.setChecked((balance.flags & Balance.FLAG_FORCE_TRANSFER) != 0);

        if (extras != null && extras.containsKey("window_title")) {
            title.setText(extras.getString("window_title"));
        }

        int sx = ((balance.flags & 0xFF) != 0 ? (balance.flags & 0xFF) - 1 : 0);
        prognosisType.setSelection(sx);
        prognosisPeriod.setText("" + balance.period);
        prognosisType.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int index, long pos) {
                switch (index) {
                    case 0:
                        blockPeriodN.setVisibility(View.GONE);
                        break;

                    case 1:
                        blockPeriodN.setVisibility(View.VISIBLE);
                        prognosisPeriodType.setText(getResources().getString(R.string.prognosis_type_dayly));
                        break;

                    case 2:
                        blockPeriodN.setVisibility(View.VISIBLE);
                        prognosisPeriodType.setText(getResources().getString(R.string.prognosis_type_weekly));
                        break;

                    case 3:
                        blockPeriodN.setVisibility(View.VISIBLE);
                        prognosisPeriodType.setText(getResources().getString(R.string.prognosis_type_monthly));
                        break;

                    case 4:
                    case 5:
                        blockPeriodN.setVisibility(View.GONE);
                        break;


                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                //To change body of implemented methods use File | Settings | File Templates.
            }
        });


        switch (balance.mode) {
            case Balance.MODE_NORMAL:
                blockTemplate.setVisibility(View.GONE);
                blockDate.setVisibility(View.VISIBLE);
                blockAmount.setVisibility(View.VISIBLE);
                blockPeriod.setVisibility(View.GONE);
                break;

            case Balance.MODE_TEMPLATE:
                blockTemplate.setVisibility(View.VISIBLE);
                blockDate.setVisibility(View.GONE);
                blockAmount.setVisibility(View.GONE);
                blockPeriod.setVisibility(View.GONE);
                break;

            case Balance.MODE_PROGNOSIS:
                blockTemplate.setVisibility(View.GONE);
                blockDate.setVisibility(View.VISIBLE);
                blockAmount.setVisibility(View.VISIBLE);
                blockPeriod.setVisibility(View.VISIBLE);
                break;
        }

        /*
        name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if(b) {
                    blockHeader.setVisibility(View.GONE);
                } else {
                    blockHeader.setVisibility(View.VISIBLE);
                }
            }
        });
        remark.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if(b) {
                    blockHeader.setVisibility(View.GONE);
                } else {
                    blockHeader.setVisibility(View.VISIBLE);
                }
            }
        });
        amount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if(b) {
                    amount.selectAll();
                    blockHeader.setVisibility(View.GONE);
                } else {
                    blockHeader.setVisibility(View.VISIBLE);
                }
            }
        });
        */

        Button wordKEY = (Button) findViewById(R.id.wordKEY);
        wordKEY.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (template.getSelectionStart() != -1) {
                    String text = template.getText().toString();
                    String sel = text.substring(
                            template.getSelectionStart(),
                            template.getSelectionEnd()
                    );
                    template.setText(
                            text.substring(0, template.getSelectionStart()) +
                                    String.format("%%KEY=%d%%", template.getSelectionEnd() - template.getSelectionStart()) +
                                    text.substring(template.getSelectionEnd()));
                    key.setText(sel);

                } else {
                    Main.toast(getApplicationContext().getResources().getString(R.string.msg_no_selection));
                }
            }
        });

        Button wordAMOUNT = (Button) findViewById(R.id.wordAMOUNT);
        wordAMOUNT.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (template.getSelectionStart() != -1) {
                    String text = template.getText().toString();
                    template.setText(
                            text.substring(0, template.getSelectionStart()) +
                                    "%AMOUNT%" +
                                    text.substring(template.getSelectionEnd()));

                } else {
                    Main.toast(getApplicationContext().getResources().getString(R.string.msg_no_selection));
                }
            }
        });

        Button wordBALANCE = (Button) findViewById(R.id.wordBALANCE);
        wordBALANCE.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (template.getSelectionStart() != -1) {
                    String text = template.getText().toString();
                    template.setText(
                            text.substring(0, template.getSelectionStart()) +
                                    "%BALANCE%" +
                                    text.substring(template.getSelectionEnd()));

                } else {
                    Main.toast(getApplicationContext().getResources().getString(R.string.msg_no_selection));
                }
            }
        });

        Button wordCURRENCY = (Button) findViewById(R.id.wordCURRENCY);
        wordCURRENCY.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (template.getSelectionStart() != -1) {
                    String text = template.getText().toString();
                    template.setText(
                            text.substring(0, template.getSelectionStart()) +
                                    ((template.getSelectionEnd() - template.getSelectionStart() == 3) ?
                                            "%CURRENCY%" :
                                            String.format("%%CURRENCY=%d%%", template.getSelectionEnd() - template.getSelectionStart())) +
                                    text.substring(template.getSelectionEnd()));

                } else {
                    Main.toast(getApplicationContext().getResources().getString(R.string.msg_no_selection));
                }
            }
        });

        Button wordIGNORE = (Button) findViewById(R.id.wordIGNORE);
        wordIGNORE.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (template.getSelectionStart() != -1) {
                    String text = template.getText().toString();
                    template.setText(
                            text.substring(0, template.getSelectionStart()) +
                                    String.format("%%IGNORE=%d%%", template.getSelectionEnd() - template.getSelectionStart()) +
                                    text.substring(template.getSelectionEnd()));

                } else {
                    Main.toast(getApplicationContext().getResources().getString(R.string.msg_no_selection));
                }
            }
        });

        Button wordTITLE = (Button) findViewById(R.id.wordTITLE);
        wordTITLE.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (template.getSelectionStart() != -1) {
                    String text = template.getText().toString();
                    template.setText(
                            text.substring(0, template.getSelectionStart()) +
                                    "%TITLE%" +
                                    text.substring(template.getSelectionEnd()));

                } else {
                    Main.toast(getApplicationContext().getResources().getString(R.string.msg_no_selection));
                }
            }
        });

        Button wordDATE = (Button) findViewById(R.id.wordDATE);
        wordDATE.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (template.getSelectionStart() != -1) {
                    final String text = template.getText().toString();
                    final int start = template.getSelectionStart();
                    final int end = template.getSelectionEnd();
                    final String sel = text.substring(start, end);

                    PopupMenu popupMenu = new PopupMenu(EditBalance.this, view);
                    popupMenu.getMenuInflater().inflate(R.menu.dmy, popupMenu.getMenu());
                    popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem item) {
                            String result = "";
                            switch (item.getItemId()) {
                                case R.id.dmy:
                                    result = parseDate("dMy", sel);
                                    break;
                                case R.id.mdy:
                                    result = parseDate("Mdy", sel);
                                    break;
                                case R.id.ymd:
                                    result = parseDate("yMd", sel);
                                    break;
                            }
                            template.setText(text.substring(0, start) + result + text.substring(end));

                            return true;
                        }
                    });
                    popupMenu.show();
                } else {
                    Main.toast(getApplicationContext().getResources().getString(R.string.msg_no_selection));
                }
            }
        });


        refreshAnalytics();
        refreshAmount();
    }

    String parseDate(String dmy, String sel) {
        String[] d = {dmy, "Hms"};
        String result = "%DATE=";
        int section = 0;
        int position = 0;
        boolean wasDigit = false;
        boolean wasLetter = false;
        for (int i = 0; i < sel.length(); ++i) {
            if (Character.isDigit(sel.charAt(i))) {
                result += d[section].substring(position, position + 1);
                wasDigit = true;
                if(wasLetter) {
                    result += "\'";
                    wasLetter = false;
                }
            } else if (sel.charAt(i) != ' ') {
                if (wasDigit && position < 2) {
                    ++position;
                }
                if(Character.isLetter(sel.charAt(i))) {
                    if(!wasLetter) {
                        result += "\'";
                    }
                    wasLetter = true;
                } else {
                    if(wasLetter) {
                        result += "\'";
                        wasLetter = false;
                    }
                }
                result += sel.substring(i, i + 1);
                wasDigit = false;
            } else {
                section = 1;
                position = 0;
                result += ' ';
                wasDigit = false;
                if(wasLetter) {
                    result += "\'";
                    wasLetter = false;
                }
            }
        }
        result += "%";
        return result;
    }

    void refreshAmount() {
        //balance.refreshComplex();
        listContainer.removeAllViews();
        int bgColor = getResources().getColor(R.color.background_color);

        amount.setText(String.format("%.2f", balance.amount));

        if (balance.type != Balance.TYPE_COMPLEX) {
            //amount.setText(String.format("%.2f",balance.amount));
            //blockComplex.setVisibility(View.GONE);
            blockTo.setVisibility(View.VISIBLE);

        } else {
            //amount.setText("0.00");
            //blockComplex.setVisibility(View.VISIBLE);
            blockTo.setVisibility(View.GONE);


            int i = 0;
            for (Complex c : balance.complex) {

                TextView ttl = Main.getTextView(context, c.name);
                ttl.setTextSize(12);
                ttl.setTypeface(Typeface.DEFAULT, Typeface.BOLD);

                TextView acc = Main.getTextView(context,
                        c.account == null
                                ? getResources().getString(R.string.transfer_empty)
                                : c.account.name);
                acc.setTextColor(Main.getAccountColor(c.account));
                acc.setTextSize(12);

                LinearLayout col = new LinearLayout(context);
                col.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                col.setOrientation(LinearLayout.VERTICAL);
                col.addView(ttl);
                col.addView(acc);


                TextView amt = Main.getTextView(context, String.format("%.2f", c.amount));
                amt.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
                amt.setTextSize(18);
                amt.setGravity(Gravity.RIGHT);

                TableRow row = Main.addRow(context, bgColor, i++, new View[]{col, amt});
                row.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        selected = balance.complex.get(view.getId());
                        //showDialog(DIALOG_CONFIRM);

                        balance.name = name.getText().toString();
                        balance.remark = remark.getText().toString();
                        balance.amount = Main.eval(amount.getText().toString(), balance.amount);

                        FragmentManager fm = getFragmentManager();
                        editNameDialog = new EditComplex(Main.db, balance, selected, adapterTo);
                        editNameDialog.show(fm, "fragment_edit_complex");

                    }
                });
                row.setFocusable(true);
                listContainer.addView(row);
            }

            TextView amt = Main.getTextView(context, String.format("%.2f", balance.amount));
            amt.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
            amt.setTextSize(18);
            amt.setTextColor(getResources().getColor(R.color.total_color));
            amt.setGravity(Gravity.RIGHT);
            amt.setPadding(0, 0, 0, 16);

            listContainer.addView(Main.addRow(context, bgColor, -1, new View[]{
                    Main.getTextView(context, ""),
                    amt
            }));
        }


    }

    void refreshAnalytics() {

        balance.recalcAnalytics();
        container.removeAllViews();
        //analyticsControls = new Spinner[balance.analytics.size()];
        //analyticsRoot = new Analytics[balance.analytics.size()];
        //analyticsIndex = 0;
        for (final Analytics section : balance.analytics.keySet()) {

            LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            llp.setMargins(0, 16, 0, 0);

            TextView title = new TextView(context);
            title.setText(section.name);
            title.setLayoutParams(llp);
            title.setTextSize(18);


            TableLayout tab = new TableLayout(context);
            tab.setColumnStretchable(0, true);
            TableRow row = new TableRow(context);
            //tab.addView(row);

            Spinner list = new Spinner(context);

            List<Analytics> values = new ArrayList<Analytics>(0);
            values.add(new Analytics(Main.db, -1, section.analyticsID, getResources().getString(R.string.transfer_empty)));
            values.addAll(Arrays.asList(section.values));

            ArrayAdapter<Analytics> adapter = new ArrayAdapter<Analytics>(context, android.R.layout.simple_spinner_item, values);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            list.setAdapter(adapter);
            list.setOnItemSelectedListener(new OnItemSelectedListener() {

                @Override
                public void onItemSelected(AdapterView<?> a, View v, int index, long pos) {
                    Analytics selected = (Analytics) a.getAdapter().getItem(index);
                    Analytics parent = balance.getParent((Analytics) a.getAdapter().getItem(index));
                    if (parent != null) {
                        balance.analytics.put(parent, selected);
                    }
                }

                public void onNothingSelected(AdapterView<?> arg0) {
                    //
                }
            });

            Analytics current = balance.analytics.get(section);
            if (current != null) {
                list.setSelection(section.getValueIndex(current) + 1, true);
            }

            Button add = new Button(context);
            add.setTag(section);
            add.setText(" + ");
            add.setWidth(44);
            add.setPadding(16,0,16,0);
            add.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    new EditAnalytics(Main.db,
                            ((Analytics)view.getTag()).analyticsID,
                            null).show(getFragmentManager(), "fragment_edit_analytics");
                    /*
                    Intent inent = new Intent(context, EditAnalytics.class);
                    inent.putExtra("parent", (Serializable) view.getTag());
                    startActivityForResult(inent, ANALYTICS_ADD);
                    */
                }
            });

            Button edit = new Button(context);
            edit.setTag(section);
            edit.setText(" .. ");
            add.setWidth(44);
            add.setPadding(16,0,16,0);
            edit.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    new EditAnalytics(Main.db,
                            ((Analytics)view.getTag()).analyticsID,
                            balance.getValue((Analytics)view.getTag())).show(getFragmentManager(), "fragment_edit_analytics");
                    /*
                    Intent inent = new Intent(context, EditAnalytics.class);
                    inent.putExtra("parent", (Serializable) view.getTag());
                    startActivityForResult(inent, ANALYTICS_ADD);
                    */
                }
            });


            row.addView(list);
            row.addView(edit);
            row.addView(add);
            tab.addView(row);

            container.addView(title);
            container.addView(tab);

        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {
            return;
        }

        switch (requestCode) {
            /*
            case ANALYTICS_ADD:
                if (resultCode == RESULT_OK) {
                    Analytics a = (Analytics) data.getSerializableExtra("analytics");
                    //Analytics p = (Analytics) data.getSerializableExtra("parent");
                    a.append();
                    for (Analytics aa : balance.analytics.keySet()) {
                        aa.refresh();
                    }
                    balance.linkVirtual(a);

                    if (balance.accountFrom != null) {
                        balance.accountFrom.refresh();
                    }
                    if (balance.accountTo != null) {
                        balance.accountTo.refresh();
                    }

                    refreshAnalytics();
                    //p.refresh();
                    //int xx = p.getValueIndex(a);
                    //currentControl.setSelection(p.getValueIndex(a) + 1, true);
                    Toast.makeText(getBaseContext(), getResources().getString(R.string.msg_analytics_added), Toast.LENGTH_SHORT).show();
                }
                break;
            case ANALYTICS_EDIT:
                Analytics a = (Analytics) data.getSerializableExtra("analytics");
                a.update();
                for (Analytics aa : balance.analytics.keySet()) {
                    aa.refresh();
                }

                if (resultCode == RESULT_OK) {
                    if (balance.accountFrom != null) {
                        balance.accountFrom.refresh();
                    }
                    if (balance.accountTo != null) {
                        balance.accountTo.refresh();
                    }
                    refreshAnalytics();
                    Toast.makeText(getBaseContext(), getResources().getString(R.string.msg_analytics_changed), Toast.LENGTH_SHORT).show();
                }
                break;
                */

            case EDIT_ACCOUNT_FROM:
                if (resultCode == RESULT_OK) {
                    Account account = (Account) data.getSerializableExtra("account");
                    if (account != null) {
                        account.update();
                        account.refresh();
                        balance.accountFrom = account;
                    }
                    refreshAnalytics();
                    Toast.makeText(context, getResources().getString(R.string.msg_account_updated)
                            + ": "
                            + account.name, Toast.LENGTH_SHORT).show();
                }
                break;

            case EDIT_ACCOUNT_TO:
                if (resultCode == RESULT_OK) {
                    Account account = (Account) data.getSerializableExtra("account");
                    if (account != null) {
                        account.update();
                        account.refresh();
                        balance.accountTo = account;
                    }
                    refreshAnalytics();
                    Toast.makeText(context, getResources().getString(R.string.msg_account_updated)
                            + ": "
                            + account.name, Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_DATE:
                DatePickerDialog tpd = new DatePickerDialog(this,
                        dateCallBack,
                        balance.date.getYear() + 1900,
                        balance.date.getMonth(),
                        balance.date.getDate());
                return tpd;

            case DIALOG_TIME:
                TimePickerDialog tpt = new TimePickerDialog(this,
                        timeCallBack,
                        balance.date.getHours(),
                        balance.date.getMinutes(),
                        true);
                return tpt;

            case DIALOG_CONFIRM:
                AlertDialog.Builder adb = new AlertDialog.Builder(this);
                adb.setTitle(getResources().getString(R.string.transfer_complex));
                adb.setMessage(selected.name + ", " + selected.amount + ", "
                        + getResources().getString(R.string.transfer_confirm_del));

                adb.setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        balance.complex.remove(selected);
                        balance.recalcComplex();
                        balance.recalcAnalytics();
                        refreshAnalytics();
                        refreshAmount();
                    }
                });
                adb.setNegativeButton(getResources().getString(R.string.no), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //
                    }
                });


                return adb.create();
        }

        return super.onCreateDialog(id);
    }

    DatePickerDialog.OnDateSetListener dateCallBack = new DatePickerDialog.OnDateSetListener() {

        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {

            balance.date.setYear(year - 1900);
            balance.date.setMonth(monthOfYear);
            balance.date.setDate(dayOfMonth);

            datePlace.setText(Main.datetimeFullString(balance.date));
        }
    };

    TimePickerDialog.OnTimeSetListener timeCallBack = new TimePickerDialog.OnTimeSetListener() {
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            balance.date.setHours(hourOfDay);
            balance.date.setMinutes(minute);
            datePlace.setText(Main.datetimeFullString(balance.date));
        }
    };

    ArrayAdapter getAccountsAdapter(int direction) {
        List<Object> accounts = new ArrayList<Object>(0);
        accounts.add(new Account(Main.db, getResources().getString(R.string.transfer_empty)));
        accounts.addAll(Arrays.asList(Main.accounts));
        if (balance.mode == Balance.MODE_NORMAL) {
            for (Balance b : Main.db.getPrognosis(Main.getViewPeriod(balance.date))) {
                if (!b.approved) {
                    if (direction == DIRECTION_TO && (b.accountFrom == null || b.accountFrom.accountID == -1)) {
                        accounts.add(b);
                    }
                    /*
                    else if (direction == DIRECTION_FROM && (b.accountTo == null || b.accountTo.accountID == -1)) {
                        accounts.add(b);
                    }
                    */
                }
            }
        }

        ArrayAdapter<Object> dataAdapter = new ArrayAdapter<Object>(this, android.R.layout.simple_spinner_item, accounts);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        return dataAdapter;
    }

    //@Override
    //public void onClick(View view) {
    //    selected = balance.complex.get(view.getId());
    //    showDialog(DIALOG_CONFIRM);
    //}

    @Override
    public boolean onAppendComplex(Complex complex) {
        balance.type = Balance.TYPE_COMPLEX;
        balance.complex.add(complex);
        if (balance.recalcComplex() < 0) {
            balance.complex.remove(complex);
            return false;
        } else {
            balance.recalcAnalytics();
            refreshAnalytics();
            refreshAmount();
            return true;
        }
    }

    @Override
    public boolean onUpdateComplex(Complex complex) {
        int ndx = balance.complex.indexOf(complex);
        Complex save = null;
        if (ndx != -1) {
            save = balance.complex.get(ndx);
            balance.complex.remove(ndx);
            balance.complex.add(ndx, complex);
        } else {
            balance.type = Balance.TYPE_COMPLEX;
            balance.complex.add(complex);
        }

        if (balance.recalcComplex() < 0) {
            if (save != null) {
                balance.complex.remove(ndx);
                balance.complex.add(ndx, save);
            } else {
                balance.complex.remove(complex);
            }
            return false;
        } else {
            balance.recalcAnalytics();
            refreshAnalytics();
            refreshAmount();
            return true;
        }
    }


    @Override
    public boolean onDeleteComplex(Complex complex) {
        selected = complex;
        showDialog(DIALOG_CONFIRM);
        return true;
    }

    @Override
    public boolean onUpdateAnalytics(Analytics analytics) {
        analytics.update();
        for (Analytics aa : balance.analytics.keySet()) {
            aa.refresh();
        }

        if (balance.accountFrom != null) {
            balance.accountFrom.refresh();
        }
        if (balance.accountTo != null) {
            balance.accountTo.refresh();
        }
        refreshAnalytics();
        Toast.makeText(getBaseContext(), getResources().getString(R.string.msg_analytics_changed), Toast.LENGTH_SHORT).show();

        return true;
    }

    @Override
    public boolean onAppendAnalytics(Analytics analytics) {
        //Analytics p = (Analytics) data.getSerializableExtra("parent");
        analytics.append();
        for (Analytics aa : balance.analytics.keySet()) {
            aa.refresh();
        }
        balance.linkVirtual(analytics);

        if (balance.accountFrom != null) {
            balance.accountFrom.refresh();
        }
        if (balance.accountTo != null) {
            balance.accountTo.refresh();
        }

        refreshAnalytics();
        //p.refresh();
        //int xx = p.getValueIndex(a);
        //currentControl.setSelection(p.getValueIndex(a) + 1, true);
        Toast.makeText(getBaseContext(), getResources().getString(R.string.msg_analytics_added), Toast.LENGTH_SHORT).show();
        return true;
    }

    @Override
    public boolean onDeleteAnalytics(Analytics analytics) {
        balance.unlinkVirtual(analytics);
        analytics.delete();
        for (Analytics aa : balance.analytics.keySet()) {
            aa.refresh();
        }

        if (balance.accountFrom != null) {
            balance.accountFrom.refresh();
        }
        if (balance.accountTo != null) {
            balance.accountTo.refresh();
        }

        refreshAnalytics();
        //p.refresh();
        //int xx = p.getValueIndex(a);
        //currentControl.setSelection(p.getValueIndex(a) + 1, true);
        Toast.makeText(getBaseContext(), getResources().getString(R.string.msg_analytics_deleted), Toast.LENGTH_SHORT).show();
        return true;
    }
}
